package controller;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class ServerController implements ServerInterface, Runnable {

    private Thread thisServer;

    private int serverPort;
    private int serverDataPort;
    private ServerSocket serverSocket;
    private boolean stop = false;
    private ExecutorService threadsPool;

    private int maxConcurrentUsers;

    public ServerController(int serverPort) {

        this.serverSocket = null;
        this.thisServer = null;

        this.serverPort = serverPort;

        threadsPool = Executors.newCachedThreadPool();

    }

    public void run() {
        synchronized (this) {
            this.thisServer = Thread.currentThread();
        }

        try {
            this.serverSocket = new ServerSocket(this.serverPort);
        } catch (IOException ex) {
            System.err.println("Error opening the server socket.");
        }
        while (!this.stop) {
            Socket clientSocket = null;
            try {
                clientSocket = this.serverSocket.accept();
            } catch (IOException ex) {
                System.err.println("Error accepting a new client.");
            }
            this.threadsPool.execute(new ClientController(clientSocket));
        }

        this.threadsPool.shutdown();

        System.out.println("Server shutdown.");
    }

    @Override
    public synchronized void shutdown() {
        this.stop = true;

        try {
            this.serverSocket.close();

        } catch (IOException ex) {
            Logger.getLogger(ServerController.class
                    .getName()).log(Level.SEVERE, null, ex);
        }

    }

}
